package cn.fboost.mtos.service.impl;

import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.request.CategoryAddRequest;
import cn.fboost.mtos.dto.request.CategoryDeleteRequest;
import cn.fboost.mtos.dto.request.CategoryUpdateRequest;
import cn.fboost.mtos.entity.Category;
import cn.fboost.mtos.mapper.CategoryMapper;
import cn.fboost.mtos.mapper.ProductMapper;
import cn.fboost.mtos.service.CategoryService;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;
    private final ProductMapper productMapper;

    public CategoryServiceImpl(CategoryMapper categoryMapper, ProductMapper productMapper) {
        this.categoryMapper = categoryMapper;
        this.productMapper = productMapper;
    }

    @Override
    public Response list() {
        return Response.builder().success().msg("获取成功").data(categoryMapper.list()).build();
    }

    @Override
    public Response add(CategoryAddRequest request) {
        Category category = new Category();
        category.setName(request.getName());
        category.setSort(request.getSort());
        if (categoryMapper.create(category) == 0) {
            return Response.builder().failure().msg("分类添加失败").build();
        }

        return Response.builder().success().msg("分类已添加").build();
    }

    @Override
    public Response delete(CategoryDeleteRequest request) {
        if (categoryMapper.findById(request.getId()) == null) {
            return Response.builder().failure().msg("分类不存在").build();
        }

        // 安全起见，分类下存在商品时不允许删除
        if (productMapper.countByCategoryId(request.getId()) > 0) {
            return Response.builder().failure().msg("分类下存在商品，无法删除").build();
        }

        if (categoryMapper.delete(request.getId()) == 0) {
            return Response.builder().failure().msg("分类删除失败").build();
        }

        return Response.builder().success().msg("分类已删除").build();
    }

    @Override
    public Response update(CategoryUpdateRequest request) {
        if (categoryMapper.findById(request.getId()) == null) {
            return Response.builder().failure().msg("分类不存在").build();
        }

        Category category = new Category();
        category.setId(request.getId());
        category.setName(request.getName());
        category.setSort(request.getSort());
        if (categoryMapper.update(category) == 0) {
            return Response.builder().failure().msg("分类信息更新失败").build();
        }

        return Response.builder().success().msg("分类信息已更新").build();
    }


}
